﻿<!DOCTYPE html>
<!--[if IE]><![endif]-->
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Exceptions </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Exceptions ">
    <meta name="generator" content="docfx 2.45.1.0">
    
    <link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../styles/docfx.css">
    <link rel="stylesheet" href="../styles/main.css">
    <meta property="docfx:navrel" content="">
    <meta property="docfx:tocrel" content="toc.html">
    <meta property="docfx:rel" content="../">
    <meta property="og:title" content="Flexible and asynchronous testing framework for ASP.NET Core MVC">
    <meta property="og:site_name" content="My Tested ASP.NET Core MVC Docs">
    <meta property="og:url" content="http://docs.mytestedasp.net/">
    <meta property="og:description" content="A fluent unit testing library for ASP.NET Core MVC">
    <meta property="og:image" content="https://mytestedasp.net/Content/Images/logosocial.jpg">
    <meta property="og:type" content="website">
    <meta property="og:locale" content="en_US">
    <meta property="twitter:card" content="summary">
    <meta property="twitter:title" content="Flexible and asynchronous testing framework for ASP.NET Core MVC">
    <meta property="twitter:description" content="A fluent unit testing library for ASP.NET Core MVC">
    <meta property="twitter:creator" content="@MyTestedASPNET">
    <meta property="twitter:url" content="https://mytestedasp.net/">
    <meta property="twitter:image" content="https://mytestedasp.net/Content/Images/logosocial.jpg">
  </head>
  <body data-spy="scroll" data-target="#affix" data-offset="120">
    <div id="wrapper">
      <header>
        <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
              </button>
              <a class="navbar-brand" href="../index.html">
                MY TESTED ASP.NET CORE MVC DOCS
              </a>
            </div>
            <div class="collapse navbar-collapse" id="navbar">
              <form class="navbar-form navbar-right" role="search" id="search">
                <div class="form-group">
                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">
                </div>
              </form>
            </div>
          </div>
        </nav>
        
        <div class="subnav navbar navbar-default">
          <div class="container hide-when-search" id="breadcrumb">
            <ul class="breadcrumb">
              <li></li>
            </ul>
          </div>
        </div>
      </header>
      <div role="main" class="container body-content hide-when-search">
        
        <div class="sidenav hide-when-search">
          <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a>
          <div class="sidetoggle collapse" id="sidetoggle">
            <div id="sidetoc"></div>
          </div>
        </div>
        <div class="article row grid-right">
          <div class="col-md-10">
            <article class="content wrap" id="_content" data-uid="">
<h1 id="exceptions">Exceptions</h1>

<p>Usually, a controller action should not throw any exceptions but rather return some result. However, that depends on the application configuration, conventions, and architecture. Let&#39;s dive deeper!</p>
<h2 id="asserting-thrown-exceptions">Asserting thrown exceptions</h2>
<p>Currently the <strong>&quot;Music Store&quot;</strong> application handles most of its potential bad requests, but there is a possible exception in the <strong>&quot;AddToCart&quot;</strong> action located in the <strong>&quot;ShoppingCartController&quot;</strong>. More specifically, this code:</p>
<pre><code class="lang-c#">var addedAlbum = await DbContext.Albums
    .SingleAsync(album =&gt; album.AlbumId == id);
</code></pre><p>If the database does not contain the provided <strong>&quot;id&quot;</strong>, our application will throw an exception. Let&#39;s assert that. Create <strong>&quot;ShoppingCartControllerTest&quot;</strong> class, add the necessary usings and write the following test:</p>
<pre><code class="lang-c#">[Fact]
public void AddToCartShouldThrowExceptionWithInvalidId()
    =&gt; MyController&lt;ShoppingCartController&gt;
        .Instance()
        .Calling(c =&gt; c.AddToCart(1, CancellationToken.None))
        .ShouldThrow() // &lt;---
        .AggregateException()
        .ContainingInnerExceptionOfType&lt;InvalidOperationException&gt;()
        .WithMessage()
        .Containing(&quot;Sequence contains no elements&quot;);
</code></pre><p>Since we do not add any entries to the scoped in-memory database, the test should pass without any problem. With it we are validating that the action throws <strong>&quot;AggregateException&quot;</strong> with inner <strong>&quot;InvalidOperationException&quot;</strong> and a message containing <strong>&quot;Sequence contains no elements&quot;</strong>. Next to the <strong>&quot;AggregateException&quot;</strong>, there is the normal <strong>&quot;Exception&quot;</strong> call, which asserts non-asynchronous errors.</p>
<h2 id="uncaught-exceptions">Uncaught exceptions</h2>
<p>Let&#39;s see what happens if the action throws an exception, and we try to validate a normal action result, for example:</p>
<pre><code class="lang-c#">[Fact]
public void AddToCartShouldThrowExceptionWithInvalidId()
    =&gt; MyController&lt;ShoppingCartController&gt;
        .Instance()
        .Calling(c =&gt; c.AddToCart(1))
        .ShouldReturn()
        .View();
</code></pre><p>As you may expect, we receive a nice and descriptive error message:</p>
<pre><code class="lang-text">When calling AddToCart action in ShoppingCartController expected no exception but AggregateException (containing InvalidOperationException with &#39;Sequence contains no elements&#39; message) was thrown without being caught.
</code></pre><h2 id="section-summary">Section summary</h2>
<p>And kids... that&#39;s how we assert thrown exceptions! :)</p>
<p>Now let&#39;s revisit our <a href="/tutorial/options.html">Options</a> testing!</p>
</article>
          </div>
          
          <div class="hidden-sm col-md-2" role="complementary">
            <div class="sideaffix">
              <div class="contribution">
                <ul class="nav">
                  <li>
                    <a href="https://github.com/tmollov/MyTested.AspNetCore.Mvc/blob/development/docs/_docfx/tutorial/exceptions.md/#L1" class="contribution-link">Improve this Doc</a>
                  </li>
                </ul>
              </div>
              <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix">
              <!-- <p><a class="back-to-top" href="#top">Back to top</a><p> -->
              </nav>
            </div>
          </div>
        </div>
      </div>
      <footer>
        <div class="grad-bottom"></div>
        <div class="footer">
          <div class="container">
            <span class="pull-right">
              <a href="#top">Back to top</a>
            </span>
            <span>Copyright © 2015-2016 <strong><a href="http://mytestedasp.net">MyTestedASP.NET</a></strong>. All Rights Reserved. Generated by <strong><a href="http://dotnet.github.io/docfx/">DocFX</a></strong></span>
          </div>
        </div>
      </footer>
    </div>
    <script type="text/javascript" src="../styles/docfx.vendor.js"></script>
    <script type="text/javascript" src="../styles/docfx.js"></script>
    <script type="text/javascript" src="../styles/main.js"></script>
    <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
      (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
      m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
      ga('create', 'UA-51720358-4', 'auto');
      ga('send', 'pageview');
    </script>
    <script>
    !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
    n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
    n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
    t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
    document,'script','https://connect.facebook.net/en_US/fbevents.js');
    fbq('init', '884740311601716');
    fbq('track', 'PageView');
    </script>
    <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=884740311601716&ev=PageView&noscript=1"></noscript>  </body>
</html>
